//
//  LRXRequestHistoryView.m
//  路人侠
//
//  Created by zhangxulong on 4/27/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXRequestHistoryView.h"
#import "LRXMyHelpItemCell.h"
#import "LRXOrderMoreView.h"
#import "MJRefresh.h"
#import "LRXAlerView.h"
#import "LRXPayViewController.h"

#import "SVProgressHUD.h"
@interface LRXRequestHistoryView()<
    UITableViewDelegate,
    UITableViewDataSource,
    LRXMyHelpItemCellDelegate,
    PayViewControllerDelegate
>

@property (nonatomic,strong) NSMutableArray * items;
@property (nonatomic,weak) UIView * alerViewMengban;
@property (nonatomic,weak) UIView * moreViewMengban;
@property (nonatomic,weak) LRXOrderMoreView * moreView;
@property (nonatomic,copy) NSString * nextPage;
@property (nonatomic,assign) NSInteger nextPageFlag;
@property (nonatomic,weak) LRXAlerView * alerView;
@property (nonatomic,copy) NSString * type;
@property (nonatomic,weak) UITableView * tableView;
@end

@implementation LRXRequestHistoryView

- (void)layoutRequestHistoryView:(NSString * )type
{
    self.type = type;
    
    self.nextPageFlag = 1;
    self.nextPage = @"1";
    self.items = [NSMutableArray array];
    self.backgroundColor = [UIColor colorWithRed:240 green:240 blue:240];
    
    UITableView * tableView = [[UITableView alloc]initWithFrame:self.bounds style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.rowHeight = 290 * hScale;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
 
    
    
    
    Reachability * reach = [Reachability reachabilityForInternetConnection];
    if ([reach currentReachabilityStatus] != NotReachable) {
        tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadHistroyData)];
        tableView.mj_footer.hidden = YES;
    }
    [SVProgressHUD showWithStatus:@"Loading..."];
    [self loadHistroyData];
    
    self.tableView = tableView;
    [self addSubview:tableView];
}

- (void)loadHistroyData
{
    AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
    NSDictionary * parm = @{@"page":self.nextPage,@"type":self.type};
    
    if (self.nextPage.length <= 0 && self.nextPageFlag == 0 ) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    else{
        [manger GET:historyUrl parameters:parm progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                NSLog(@"%@",responseObject);
                NSInteger statusCode = [responseObject[@"data"][@"status_code"] integerValue];
                if (statusCode == 1) {
                    self.nextPageFlag = 0;
                    self.nextPage = responseObject[@"data"][@"next_page"];
                    NSArray * contents = responseObject[@"data"][@"dataset"];
                    for (NSDictionary * dic in contents) {
                        LRXHelpMeInfoModel * thingModel = [LRXHelpMeInfoModel helpModelWithDic:dic];
                        [self.items addObject:thingModel];
                    }
                    [self.tableView reloadData];
                }
                if (self.items.count < 3) {
                    self.tableView.mj_footer.hidden = YES;
                }
                else
                {
                    self.tableView.mj_footer.hidden = NO;
                }
                [self.tableView.mj_footer endRefreshing];
            });
      
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [SVProgressHUD dismiss];
            [self.tableView.mj_footer endRefreshing];
            NSLog(@"%@",error);
        }];

    }
    

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * REMYHELPITEM = @"REMYHELPITEM";
    LRXMyHelpItemCell * cell = [tableView dequeueReusableCellWithIdentifier:REMYHELPITEM];
    if (cell == nil) {
        cell = [[LRXMyHelpItemCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:REMYHELPITEM];
    }
    
    [cell layoutSubviews:self.items[indexPath.section]];
    cell.row = indexPath.section;
    cell.myHelpMoreInfoDelegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20 * hScale;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIView * backgroundView1 = [[UIView alloc]init];
    backgroundView1.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.54];
    backgroundView1.frame = CGRectMake(0, 0, 640 * wScale, MainScreenH);
    //手势 点击
    UITapGestureRecognizer * pin1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(moreViewMengbanClick)];
    [backgroundView1 addGestureRecognizer:pin1];
    
    [[UIApplication sharedApplication].keyWindow addSubview:backgroundView1];
    LRXOrderMoreView * moreView = [[LRXOrderMoreView alloc]init];
    moreView.frame = CGRectMake(0,0, MainScreenW - 100 * wScale, 0);
    [moreView layoutOrderMoreView:self.items[indexPath.section]];
    
    moreView.frame = CGRectMake(0,0, MainScreenW - 100 * wScale, moreView.maxHeight);
    moreView.center = CGPointMake(MainScreenW * 0.5, MainScreenH * 0.5);
    
    
    
    [[UIApplication sharedApplication].keyWindow addSubview:moreView];
    
    self.moreView = moreView;
    self.moreViewMengban = backgroundView1;
    
    
    CAKeyframeAnimation * bringAni = [CAKeyframeAnimation animation];
    bringAni.keyPath = @"transform.scale";
    bringAni.values = @[@0,@1];
    bringAni.duration = 0.15;
    [moreView.layer addAnimation:bringAni forKey:nil];
}
#pragma mark - LRXMyHelpItemCell的代理方法
/**
 *  弹出警告视图
 *
 *  @param cell 点击完成订单的cell
 *  @param row  订单的行数
 */
- (void)pushReceiveAlerView:(LRXMyHelpItemCell *)cell withRow:(NSInteger)row
{
    
    UIView * backgroundView = [[UIView alloc]init];
    backgroundView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.54];
    backgroundView.frame = CGRectMake(0,  0, 640 * wScale, MainScreenH);
    [self addSubview:backgroundView];
    
    self.alerViewMengban = backgroundView;
    //手势 点击
    UITapGestureRecognizer * pin1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(mengbanClick)];
    [backgroundView addGestureRecognizer:pin1];
    
    LRXAlerView * alerView = [LRXAlerView AlerView:@"是否确定收货" withMeg:@"确认收货后（然后呢？？？）"];
    CAKeyframeAnimation * bringAni = [CAKeyframeAnimation animation];
    bringAni.keyPath = @"transform.scale";
    bringAni.values = @[@0,@1.2,@1];
    bringAni.duration = 0.2;
    [alerView.layer addAnimation:bringAni forKey:nil];
    
    self.alerView = alerView;
    [self addSubview:alerView];

}


/**
 *  点击cell付款的按钮调用付款借口
 *
 *  @param cell 点击完成订单的cell
 *  @param row  订单的行数
 */
- (void)pushPayFunction:(LRXMyHelpItemCell *)cell withRow:(NSInteger)row
{
    LRXHelpMeInfoModel * cellModel = self.items[row];
    
    AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
    NSDictionary * parme = @{@"w_id":cellModel.itemID,@"type":@"1"};
    [manger POST:payForRequestUrl parameters:parme progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"%@",responseObject);
            
            NSString * sign = responseObject[@"data"][@"sign"];
            NSString * tradeNO = cellModel.itemID;
            
            LRXPayViewController * payController = [[LRXPayViewController alloc]init];
            payController.tradeNO = tradeNO;
            payController.sign = sign;
            payController.buyThingArray = cellModel.thingArray;
            payController.payDelegate = self;
            
            [payController formatConvert];
            
        });
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
/**
 *  完成订单，点击确认收货
 *
 *  @param cell 点击完成订单的cell
 *  @param row  订单的行数
 */
- (void)pushFinishOrder:(LRXMyHelpItemCell *)cell withRow:(NSInteger)row
{
  
    LRXHelpMeInfoModel * cellModel = self.items[row];

    AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
    NSString * itemID =  [LRXBlowFish enCodeBlowfishWithValue:cellModel.itemID withKeyStr:blowFishKey];
    NSDictionary * parme = @{@"w_q_id":itemID};
  
    
    [manger POST:waiterRequestFinishUrl parameters:parme progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@" %@ %@",parme,responseObject);
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSInteger statusCode = [responseObject[@"data"][@"status_code"] integerValue];
            if (statusCode == 1) {
                NSIndexPath * rowPath = [self.tableView indexPathForCell:cell];
                [self.items removeObjectAtIndex:row];
                NSIndexSet * setIndex = [NSIndexSet indexSetWithIndex:rowPath.section];
                [self.tableView deleteSections:setIndex withRowAnimation:UITableViewRowAnimationFade];
                
                if ([self.requestHistoryDelegate respondsToSelector:@selector(loadOtherHistroyData)]) {
                    [self.requestHistoryDelegate loadOtherHistroyData];
                }
            }
            else if(statusCode == 3)
            {
                [MBProgressHUD showError:@"请求失败"];
            }
        });
    
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [MBProgressHUD showError:@"网络出现错误"];
        
    }];
}


#pragma mark - payOrderViewDelegate
- (void)payForOrderResult:(NSString *)resultStatus
{
    //支付成功
    if ([resultStatus isEqualToString:@"9000"]) {
        
    }
    else  //支付失败
    {
        
    }
}
- (void)mengbanClick
{
    
    CAKeyframeAnimation * moreAni = [CAKeyframeAnimation animation];
    moreAni.keyPath = @"transform.scale";
    moreAni.values = @[@1,@0];
    moreAni.duration = 0.15;
    moreAni.removedOnCompletion=NO;
    moreAni.fillMode=kCAFillModeForwards;
    
    [self.alerView.layer addAnimation:moreAni forKey:nil];
    
    //延时删除
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.alerViewMengban removeFromSuperview];
        [self.alerView removeFromSuperview];
        
    });
    
}

- (void)moreViewMengbanClick
{
    //当移除 蒙板 导航栏中的左按钮不可用
    //收缩动画
    CAKeyframeAnimation * moreAni = [CAKeyframeAnimation animation];
    moreAni.keyPath = @"transform.scale";
    moreAni.values = @[@1,@0];
    moreAni.duration = 0.15;
    moreAni.removedOnCompletion=NO;
    moreAni.fillMode=kCAFillModeForwards;
    
    [self.moreView.layer addAnimation:moreAni forKey:nil];
    
    //延时删除
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.moreViewMengban removeFromSuperview];
        [self.moreView removeFromSuperview];
        
    });
}



@end
